package top.alanshelby.mybatis.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class MyDateTypeHandler extends BaseTypeHandler<Date> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, String.valueOf(parameter.getTime()));
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlTimetamp = rs.getString(columnName);
        if (null != sqlTimetamp) {
            return new Date(Long.valueOf(sqlTimetamp));
        }
        return null;
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlTimetamp = rs.getString(columnIndex);
        if (null != sqlTimetamp) {
            return new Date(Long.valueOf(sqlTimetamp));
        }
        return null;
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlTimetamp = cs.getString(columnIndex);
        if (null != sqlTimetamp) {
            return new Date(Long.valueOf(sqlTimetamp));
        }
        return null;
    }
}